package com.hxs.hxsserver.controller;

import com.hxs.hxsserver.domain.entity.user.User;
import com.hxs.hxsserver.exception.TokenInvalidException;
import com.hxs.hxsserver.mapper.user.UserMapper;
import com.hxs.hxsserver.utils.JwtTokenUtil;
import com.hxs.hxsserver.config.redis.RedisService;
import com.hxs.hxsserver.config.redis.UserKey;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 基本控制器
 *
 * @author Andi
 * @date 2021/01/14
 */
@RestController
public class BaseController {
    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected HttpServletResponse response;
    @Resource
    private RedisService redisService;
    @Resource
    private UserMapper userMapper;

    /**
     * 获取用户Id
     *
     * @return {@link String}
     */
    public Integer getUserId() {
        if (StringUtils.isNotBlank(request.getHeader("Authorization"))) {
            String token = redisService.get(UserKey.userToken, request.getHeader("Authorization"), String.class);
            if (StringUtils.isBlank(token)) {
                throw new TokenInvalidException();
            }
            Claims claims = JwtTokenUtil.parseToken(request.getHeader("Authorization"));
            return claims.get("userId", Integer.class);
        }
        throw new TokenInvalidException();
    }

    /**
     * 获取用户
     * @return
     */
    public User getUser() {
        if (StringUtils.isNotBlank(request.getHeader("Authorization"))) {
            String token = redisService.get(UserKey.userToken, request.getHeader("Authorization"), String.class);
            if (StringUtils.isBlank(token)) {
                throw new TokenInvalidException();
            }
            Claims claims = JwtTokenUtil.parseToken(request.getHeader("Authorization"));
            Integer userId = claims.get("userId", Integer.class);
            return userMapper.selectById(userId);
        }
        throw new TokenInvalidException();
    }
}
